#include <errno.h>
#include <stdio.h>
#include <stagfs_fuse.h>

static struct fuse_operations stagfs_fuseobj =
{
  .getattr = stagfs_getattr,
  .readlink = stagfs_readlink,
  .mknod = stagfs_mknod,
  .mkdir = stagfs_mkdir,
  .unlink = stagfs_unlink,
  .rmdir = stagfs_rmdir,
  .symlink = stagfs_symlink,
  .rename = stagfs_rename,
  .link = stagfs_link,
  .chmod = stagfs_chmod,
  .chown = stagfs_chown,
  .truncate = stagfs_truncate,
  .utime = stagfs_utime,
  .open = stagfs_open,
  .read = stagfs_read,
  .write = stagfs_write,
  .statfs = stagfs_statfs,
  .flush = stagfs_flush,
  .release = stagfs_release,
  .fsync = stagfs_fsync,
  .setxattr = stagfs_setxattr,
  .getxattr = stagfs_getxattr,
  .listxattr = stagfs_listxattr,
  .removexattr = stagfs_removexattr,
  .opendir = stagfs_opendir,
  .readdir = stagfs_readdir,
  .releasedir = stagfs_releasedir,
  .fsyncdir = stagfs_fsyncdir,
  .init = stagfs_init,
  .destroy = stagfs_destroy,
  .access = stagfs_access,
  .create = stagfs_create,
  .ftruncate = stagfs_ftruncate,
  .fgetattr = stagfs_fgetattr,
  .lock = stagfs_lock,
  .utimens = stagfs_utimens,
  .bmap = stagfs_bmap,
  .ioctl = stagfs_ioctl,
  .poll = stagfs_poll
};

// ---------------------------------------------------------------------------
int main(int argc, char **argv)
// ---------------------------------------------------------------------------
{
  if (argc == 3 || argc == 4)
  {
    struct stat nod;
    if (stat(argv[1], &nod) != 0)
    {
      printf("Error: Couldn't stat source node: %s", strerror(errno));
      return 1;
    }
    
    FILE* fs = fopen(argv[1], "r+");

    if (fs == NULL)
    {
      printf("Error: Couldn't open source node: %s\n", strerror(errno));
      return 1;
    }

    if (tagfs.init(fs) == false)
    {
      fclose(fs);
      printf("Error: Source node is not a SimpleTagFS filesystem.\n");
      return 1;
    }
    char* fuse_argv[5];
    std::string argv_strings[3];
    argv_strings[0] = "-o";
    argv_strings[1] = "big_writes,atomic_o_trunc,ac_attr_timeout=1,default_permissions,hard_remove,fsname=SimpleTagFS,max_read=65535,max_write=65535";
    argv_strings[2] = "-d";
    fuse_argv[0] = argv[0];
    fuse_argv[1] = argv[2];
    fuse_argv[2] = (char*)argv_strings[0].data();
    fuse_argv[3] = (char*)argv_strings[1].data();
    fuse_argv[4] = (char*)argv_strings[2].data();
    if (argc == 4)
    {
      return fuse_main(5, fuse_argv, tag_fuse_make(), NULL);      
    }   
    return fuse_main(4, fuse_argv, tag_fuse_make(), NULL);
  }
  else
  {
    print_help();
    return EXIT_FAILURE;
  }
}
